<script setup lang="ts">
import { ref, watch } from 'vue'
import { changePassword } from '../services/auth'

/**
 * 修改密码弹窗组件
 * 用于用户修改密码操作
 */

interface Props {
  show: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  close: []
  success: []
}>()

const oldPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const isLoading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

/**
 * 监听弹窗显示状态，重置表单
 */
watch(
  () => props.show,
  (newShow) => {
    if (newShow) {
      oldPassword.value = ''
      newPassword.value = ''
      confirmPassword.value = ''
      isLoading.value = false
      errorMessage.value = ''
      successMessage.value = ''
      // 延迟聚焦，确保DOM已渲染
      setTimeout(() => {
        const input = document.querySelector('.password-input') as HTMLInputElement
        if (input) {
          input.focus()
        }
      }, 100)
    }
  }
)

/**
 * 处理修改密码
 */
const handleChangePassword = async (): Promise<void> => {
  const trimmedOldPassword = oldPassword.value.trim()
  const trimmedNewPassword = newPassword.value.trim()
  const trimmedConfirmPassword = confirmPassword.value.trim()

  if (!trimmedOldPassword || !trimmedNewPassword || !trimmedConfirmPassword) {
    errorMessage.value = '请填写所有字段'
    return
  }

  if (trimmedNewPassword !== trimmedConfirmPassword) {
    errorMessage.value = '新密码和确认密码不一致'
    return
  }

  if (trimmedNewPassword.length < 6) {
    errorMessage.value = '新密码长度至少为6位'
    return
  }

  isLoading.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    const result = await changePassword(trimmedOldPassword, trimmedNewPassword)

    if (result.success) {
      successMessage.value = result.message || '密码修改成功'
      emit('success')
      // 延迟关闭弹窗，让用户看到成功消息
      setTimeout(() => {
        handleClose()
      }, 1500)
    } else {
      errorMessage.value = result.message || '密码修改失败'
    }
  } catch (error) {
    console.error('修改密码过程中发生错误:', error)
    errorMessage.value = '修改密码过程中发生错误'
  } finally {
    isLoading.value = false
  }
}

/**
 * 关闭弹窗
 */
const handleClose = (): void => {
  oldPassword.value = ''
  newPassword.value = ''
  confirmPassword.value = ''
  isLoading.value = false
  errorMessage.value = ''
  successMessage.value = ''
  emit('close')
}

/**
 * 处理键盘事件
 * @param event 键盘事件
 */
const handleKeydown = (event: KeyboardEvent): void => {
  if (event.key === 'Enter') {
    handleChangePassword()
  } else if (event.key === 'Escape') {
    handleClose()
  }
}
</script>

<template>
  <div v-if="show" class="modal-overlay" @click="handleClose">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">修改密码</h3>
        <button class="close-btn" @click="handleClose">
          <svg viewBox="0 0 24 24" width="20" height="20">
            <path
              fill="currentColor"
              d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
            />
          </svg>
        </button>
      </div>

      <div class="modal-body">
        <!-- 错误和成功消息 -->
        <div v-if="errorMessage" class="message error-message">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
          </svg>
          {{ errorMessage }}
        </div>
        <div v-if="successMessage" class="message success-message">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
          </svg>
          {{ successMessage }}
        </div>

        <div class="form-group">
          <label class="form-label">当前密码</label>
          <input
            v-model="oldPassword"
            @keydown="handleKeydown"
            type="password"
            class="password-input"
            placeholder="请输入当前密码"
            :disabled="isLoading"
          />
        </div>

        <div class="form-group">
          <label class="form-label">新密码</label>
          <input
            v-model="newPassword"
            @keydown="handleKeydown"
            type="password"
            class="password-input"
            placeholder="请输入新密码（至少6位）"
            :disabled="isLoading"
          />
        </div>

        <div class="form-group">
          <label class="form-label">确认新密码</label>
          <input
            v-model="confirmPassword"
            @keydown="handleKeydown"
            type="password"
            class="password-input"
            placeholder="请再次输入新密码"
            :disabled="isLoading"
          />
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-cancel" @click="handleClose" :disabled="isLoading">取消</button>
        <button
          class="btn btn-change"
          @click="handleChangePassword"
          :disabled="!oldPassword.trim() || !newPassword.trim() || !confirmPassword.trim() || isLoading"
        >
          <span v-if="isLoading" class="loading-spinner"></span>
          {{ isLoading ? '修改中...' : '修改密码' }}
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #e9ecef;
}

.modal-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

.close-btn {
  padding: 4px;
  border: none;
  border-radius: 4px;
  background: transparent;
  cursor: pointer;
  color: #6c757d;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f8f9fa;
  color: #495057;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.password-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.password-input:focus {
  border-color: #007bff;
}

.password-input:disabled {
  background: #f8f9fa;
  cursor: not-allowed;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid #e9ecef;
}

.btn {
  padding: 10px 20px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-cancel {
  background: white;
  color: #6c757d;
}

.btn-cancel:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #adb5bd;
}

.btn-change {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.btn-change:hover:not(:disabled) {
  background: #0056b3;
  border-color: #0056b3;
}

.btn:disabled {
  background: #e9ecef;
  color: #6c757d;
  border-color: #dee2e6;
  cursor: not-allowed;
}

.loading-spinner {
  width: 14px;
  height: 14px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
  font-size: 14px;
}

.error-message {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.success-message {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}
</style>